const path = require('path');
const fs = require("fs");
const labelMapping = require('./label-mapping');

const docsDir = path.join(__dirname, '../');

const getMappedTitle = (title) => {
    if (title in labelMapping) {
        return labelMapping[title];
    }
    return title;
};

function isExcludeDirs(dir) {
    return dir.startsWith('.') || ['en'].includes(dir)
}

const getGroupInfo = (pathname, title, origin = '/') => {
    const files = fs.readdirSync(pathname);
    const validFiles = files
        .map(f => {
            const state = fs.statSync(path.join(pathname, f));
            return {
                state,
                filename: f,
                filepath: path.join(pathname, f)
            }
        })
        .filter(({state, filename}) => (state.isDirectory() || filename.toLowerCase().endsWith('.md')) && !isExcludeDirs(filename))
    return {
        ...validFiles.find(f => f.filename.toLowerCase() === 'readme.md') ? {
            path: origin
        } : {},
        title: getMappedTitle(title),
        sidebarDepth: 2,
        children: validFiles.map(
            ({state, filename, filepath}) => {
                let result = origin + filename + '/'
                if (state.isFile() && filename.toLowerCase() !== 'readme.md') {
                    let result = origin + filename
                    return result.replace(/\.md/i, '')
                }
                if (state.isDirectory()) {
                    return getGroupInfo(filepath, filename, result);
                }
            }
        ).filter(f => f)
    }
}

const getRootPages = (pathname, home = '主页', baseUrl = '/') => {
    console.log(pathname);
    const files = fs.readdirSync(pathname);
    const validFiles = files
        .map(f => {
            const state = fs.statSync(path.join(pathname, f));
            return {
                state,
                filename: f,
                filepath: path.join(pathname, f)
            }
        })
        .filter(
            ({state, filename}) => state.isDirectory() && !isExcludeDirs(filename)
        );

    console.log(validFiles);

    const result = validFiles
        .map(({filename, filepath}) => [
            '/' + filename + '/', getGroupInfo(filepath, filename, '/' + filename + '/')
        ])
        .reduce((result = {}, [key, value]) => Object.assign(result, {[key]: [value]}), {});

    result[''] = [getGroupInfo(pathname, home, baseUrl)];
    console.log(result);
    return result;
}

// .vuepress/config.js
module.exports = {
    locales: {
        '/': {
            lang: 'zh-CN',
            title: '苍石居',
            description: ''
        },
        '/en/': {
            lang: 'en-US',
            title: 'LIVE Cangshi',
            description: ''
        }
    },
    themeConfig: {
        locales: {
            '/': {
                // 多语言下拉菜单的标题
                selectText: '选择语言',
                // 该语言在下拉菜单中的标签
                label: '简体中文',
                nav: [
                    {text: '首页', link: '/'},
                ],
                sidebar: getRootPages(docsDir),
                lastUpdated: '上次编辑', // string | boolean
                logo: '/image/logo-1.png',
                smoothScroll: true,
                // title: '计时器掌控者',
                description: ''
            },
            '/en/': {
                selectText: 'Languages',
                label: 'English',
                nav: [
                    {text: 'Home', link: '/en/'},
                ],
                sidebar: getRootPages(path.join(docsDir, './en'), 'Home', '/en/'),
                lastUpdated: 'Last Modified', // string | boolean
                logo: '/image/logo-1.png',
                smoothScroll: true,
                // title: 'Timer Hooker',
                description: ''
            }
        }
    },
    port: '4044'
}
